<template>
  <div class="weather-load-correlation">
    <div class="header">
      <h2>气象负荷相关性分析</h2>
      <div class="controls">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-button type="primary" @click="analyzeCorrelation" :loading="loading">
          分析相关性
        </el-button>
      </div>
    </div>

    <div v-if="correlationData" class="analysis-content">
      <!-- 相关性概览 -->
      <el-card class="correlation-overview">
        <template #header>
          <span>相关性概览</span>
        </template>
        <div class="correlation-cards">
          <div 
            v-for="(feature, key) in correlationData.correlation_analysis" 
            :key="key"
            class="correlation-card"
            :class="getImpactClass(feature.impact_level)"
          >
            <div class="feature-name">{{ getFeatureName(key) }}</div>
            <div class="correlation-value">
              {{ feature.pearson_correlation > 0 ? '+' : '' }}{{ feature.pearson_correlation }}
            </div>
            <div class="impact-level">{{ feature.impact_level }}</div>
            <div class="description">{{ feature.description }}</div>
          </div>
        </div>
      </el-card>

      <!-- 散点图 -->
      <el-card class="scatter-plots">
        <template #header>
          <span>散点图分析</span>
        </template>
        <div class="scatter-container">
          <div 
            v-for="(plot, key) in correlationData.scatter_plots" 
            :key="key"
            class="scatter-plot"
          >
            <div ref="scatterChart" :id="`scatter-${key}`" class="chart"></div>
          </div>
        </div>
      </el-card>

      <!-- 时间序列图 -->
      <el-card class="time-series">
        <template #header>
          <span>时间序列分析</span>
        </template>
        <div ref="timeSeriesChart" class="chart"></div>
      </el-card>

      <!-- 统计摘要 -->
      <el-card class="statistics-summary">
        <template #header>
          <span>统计摘要</span>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="分析天数">
            {{ correlationData.summary.total_days }} 天
          </el-descriptions-item>
          <el-descriptions-item label="分析期间">
            {{ correlationData.summary.analysis_period.start_date }} 至 {{ correlationData.summary.analysis_period.end_date }}
          </el-descriptions-item>
          <el-descriptions-item label="最强相关性">
            {{ getFeatureName(correlationData.summary.strongest_correlation[0]) }}: 
            {{ correlationData.summary.strongest_correlation[1] > 0 ? '+' : '' }}{{ correlationData.summary.strongest_correlation[1] }}
          </el-descriptions-item>
          <el-descriptions-item label="最弱相关性">
            {{ getFeatureName(correlationData.summary.weakest_correlation[0]) }}: 
            {{ correlationData.summary.weakest_correlation[1] > 0 ? '+' : '' }}{{ correlationData.summary.weakest_correlation[1] }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>

    <div v-else-if="!loading" class="empty-state">
      <el-empty description="请选择日期范围并点击分析按钮开始分析" />
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { predictionAPI } from '@/utils/api'

export default {
  name: 'WeatherLoadCorrelation',
  data() {
    return {
      dateRange: null,
      loading: false,
      correlationData: null,
      charts: {}
    }
  },
  mounted() {
    // 设置默认日期范围为最近3个月
    const endDate = new Date()
    const startDate = new Date()
    startDate.setMonth(startDate.getMonth() - 3)
    
    this.dateRange = [
      startDate.toISOString().split('T')[0],
      endDate.toISOString().split('T')[0]
    ]
  },
  methods: {
    handleDateChange() {
      // 日期变化时的处理
    },
    
    async analyzeCorrelation() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.warning('请选择日期范围')
        return
      }
      
      this.loading = true
      try {
        const response = await predictionAPI.getWeatherLoadCorrelation(
          this.dateRange[0],
          this.dateRange[1]
        )
        
        if (response.success) {
          this.correlationData = response.data
          this.$nextTick(() => {
            this.renderCharts()
          })
          this.$message.success('相关性分析完成')
        } else {
          this.$message.error(response.message || '分析失败')
        }
      } catch (error) {
        console.error('相关性分析失败:', error)
        this.$message.error('分析失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    getFeatureName(key) {
      const nameMap = {
        'temp_max': '最高温度',
        'temp_min': '最低温度',
        'precip': '降水量',
        'humidity': '湿度'
      }
      return nameMap[key] || key
    },
    
    getImpactClass(impactLevel) {
      const classMap = {
        '强相关': 'strong-correlation',
        '中等相关': 'medium-correlation',
        '弱相关': 'weak-correlation',
        '无相关': 'no-correlation'
      }
      return classMap[impactLevel] || 'no-correlation'
    },
    
    renderCharts() {
      if (!this.correlationData) return
      
      // 渲染散点图
      this.renderScatterPlots()
      
      // 渲染时间序列图
      this.renderTimeSeriesChart()
    },
    
    renderScatterPlots() {
      const scatterPlots = this.correlationData.scatter_plots
      
      Object.keys(scatterPlots).forEach(key => {
        const chartId = `scatter-${key}`
        const chartElement = document.getElementById(chartId)
        
        if (chartElement) {
          // 销毁旧图表
          if (this.charts[chartId]) {
            this.charts[chartId].dispose()
          }
          
          const chart = echarts.init(chartElement)
          this.charts[chartId] = chart
          
          const plotData = scatterPlots[key]
          const correlation = this.correlationData.correlation_analysis[key]
          
          const option = {
            title: {
              text: plotData.title,
              left: 'center',
              textStyle: {
                fontSize: 14
              }
            },
            tooltip: {
              trigger: 'axis',
              formatter: function(params) {
                const data = params[0]
                return `${plotData.title}<br/>
                        负荷: ${data.value[1].toFixed(2)} MW<br/>
                        ${getFeatureName(key)}: ${data.value[0].toFixed(2)} ${getUnit(key)}`
              }
            },
            xAxis: {
              type: 'value',
              name: getFeatureName(key),
              nameLocation: 'middle',
              nameGap: 30
            },
            yAxis: {
              type: 'value',
              name: '负荷 (MW)',
              nameLocation: 'middle',
              nameGap: 40
            },
            series: [{
              type: 'scatter',
              data: plotData.x.map((x, i) => [x, plotData.y[i]]),
              symbolSize: 6,
              itemStyle: {
                color: correlation.pearson_correlation > 0 ? '#ff6b6b' : '#4ecdc4'
              }
            }],
            grid: {
              left: '10%',
              right: '10%',
              top: '15%',
              bottom: '15%'
            }
          }
          
          chart.setOption(option)
        }
      })
    },
    
    renderTimeSeriesChart() {
      const timeSeriesElement = this.$refs.timeSeriesChart
      if (!timeSeriesElement) return
      
      // 销毁旧图表
      if (this.charts['timeSeries']) {
        this.charts['timeSeries'].dispose()
      }
      
      const chart = echarts.init(timeSeriesElement)
      this.charts['timeSeries'] = chart
      
      const timeSeriesData = this.correlationData.time_series
      
      const option = {
        title: {
          text: '气象特征与负荷时间序列',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['负荷', '最高温度', '最低温度', '降水量', '湿度'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: timeSeriesData.dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '负荷 (MW)',
            position: 'left'
          },
          {
            type: 'value',
            name: '温度 (°C)',
            position: 'right',
            offset: 80
          },
          {
            type: 'value',
            name: '降水量 (mm) / 湿度 (%)',
            position: 'right'
          }
        ],
        series: [
          {
            name: '负荷',
            type: 'line',
            yAxisIndex: 0,
            data: timeSeriesData.loads,
            itemStyle: { color: '#5470c6' }
          },
          {
            name: '最高温度',
            type: 'line',
            yAxisIndex: 1,
            data: timeSeriesData.temp_max,
            itemStyle: { color: '#ff6b6b' }
          },
          {
            name: '最低温度',
            type: 'line',
            yAxisIndex: 1,
            data: timeSeriesData.temp_min,
            itemStyle: { color: '#4ecdc4' }
          },
          {
            name: '降水量',
            type: 'line',
            yAxisIndex: 2,
            data: timeSeriesData.precip,
            itemStyle: { color: '#45b7d1' }
          },
          {
            name: '湿度',
            type: 'line',
            yAxisIndex: 2,
            data: timeSeriesData.humidity,
            itemStyle: { color: '#96ceb4' }
          }
        ]
      }
      
      chart.setOption(option)
    }
  },
  
  beforeUnmount() {
    // 清理图表
    Object.values(this.charts).forEach(chart => {
      if (chart && typeof chart.dispose === 'function') {
        chart.dispose()
      }
    })
  }
}

function getFeatureName(key) {
  const nameMap = {
    'temp_max': '最高温度',
    'temp_min': '最低温度',
    'precip': '降水量',
    'humidity': '湿度'
  }
  return nameMap[key] || key
}

function getUnit(key) {
  const unitMap = {
    'temp_max': '°C',
    'temp_min': '°C',
    'precip': 'mm',
    'humidity': '%'
  }
  return unitMap[key] || ''
}
</script>

<style scoped>
.weather-load-correlation {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.analysis-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.correlation-overview {
  margin-bottom: 20px;
}

.correlation-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.correlation-card {
  padding: 15px;
  border-radius: 8px;
  text-align: center;
  transition: transform 0.2s;
}

.correlation-card:hover {
  transform: translateY(-2px);
}

.correlation-card.strong-correlation {
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
  color: white;
}

.correlation-card.medium-correlation {
  background: linear-gradient(135deg, #4ecdc4, #6ee7df);
  color: white;
}

.correlation-card.weak-correlation {
  background: linear-gradient(135deg, #45b7d1, #6bc5d8);
  color: white;
}

.correlation-card.no-correlation {
  background: linear-gradient(135deg, #96ceb4, #a8d5c0);
  color: white;
}

.feature-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.correlation-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.impact-level {
  font-size: 14px;
  margin-bottom: 8px;
  opacity: 0.9;
}

.description {
  font-size: 12px;
  opacity: 0.8;
}

.scatter-plots {
  margin-bottom: 20px;
}

.scatter-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.scatter-plot {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.time-series {
  margin-bottom: 20px;
}

.time-series .chart {
  height: 400px;
}

.statistics-summary {
  margin-bottom: 20px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}
</style> 